package com.sandmens.droidvdr;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class Recordings extends ListActivity {

	private ViewFlipper flipper_main_recording;
	private ArrayList<String> Recording_Name;
	private ArrayList<String> Recording_Url;
	private ArrayList<String> Recording_Description;
	String Error_Description = "";
	boolean main_recordings_is_Active = true;
  	private String Rec_Name ="";
  	private String Rec_Subtitle = "";
  	private String Rec_Url = "";
  	private File File_Handler = null;
    private ProgressDialog myProgressDialog = null;
  	private Integer StartPos = 0;
  	private Integer EndPos = 0;
  	private String myLine = "";
	private String URL_start_vlc = "";

	private ArrayList<HashMap<String,String>> list_recording = new ArrayList<HashMap<String,String>>();
	private SimpleAdapter adapEntries_recordings = null;
	private Integer n;
	private String URL_mvdr = "";
	private String URL_stream = "";
  	public static final String PREFS_NAME = "droidVDRsettings";
	// State for Connection
    private String State_Connection_Message = "";
    private ConnectivityManager con_manager;
    private NetworkInfo[] netInfo_array;
    private Integer NetworkSpeed_Availible = -1;
    private boolean Use_AutoSpeed = false;
    private boolean Use_High = false;
    private boolean Use_Middle = false;
    private boolean Use_Low = false;
  	private Integer Selected_Recording_Index =0;
  	private boolean Coming_from_Player = false;
    private boolean Check_Passwd = false;
    private String HTML_Passwd = "";
    private String HTML_User = "";
	private String login = "";
	private String password = "";
	private Boolean Use_UTF8 = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        setContentView(R.layout.recordings);
        ReadSettings();
        flipper_main_recording = (ViewFlipper) findViewById(R.id.flipper_main_records_);
        
        Bundle b = this.getIntent().getExtras();
        URL_mvdr = b.getString("URL");
        URL_stream = b.getString("STREAM_URL");
        
    	//flipper_main_recording
    	if ( Recording_Name == null)
    		Recording_Name = new ArrayList<String>();
    	else
    		Recording_Name.clear();
    	if ( Recording_Url == null)
    		Recording_Url  = new ArrayList<String>();
    	else
    		Recording_Url.clear();
    	if ( Recording_Description == null)
    		Recording_Description  = new ArrayList<String>();
    	else
    		Recording_Description.clear();
    	
    	RecordingProcessing();
	}
	
	@Override
    protected void onResume()
    {
		super.onResume();
		if ( Coming_from_Player)
		{
	        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			PlayerStopProcessing();
		}
    }
  	
  	private void ReadSettings()
  	{
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        Use_AutoSpeed = settings.getBoolean("network_use_auto", false);
        Use_High = settings.getBoolean("network_use_high", false);
        Use_Middle = settings.getBoolean("network_use_middle", false);
        Use_Low = settings.getBoolean("network_use_low", true);
    	Check_Passwd = settings.getBoolean("network1_use_passwd", false);
    	if (Check_Passwd )
    	{
	    	HTML_User = settings.getString("network1_user", "user");
	    	HTML_Passwd = settings.getString("network1_passwd", "passwd");
    	}
    	else
    	{
	    	Check_Passwd = settings.getBoolean("network2_use_passwd", false);
	    	if (Check_Passwd )
	    	{
		    	HTML_User = settings.getString("network2_user", "user");
		    	HTML_Passwd = settings.getString("network2_passwd", "passwd");
	    	}
    	}
    	Use_UTF8 = settings.getBoolean("use_utf8", false);
  	 }

    private Integer Check_Network()
    {
		con_manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
		if ( con_manager == null)
		{
			State_Connection_Message = "no comManager active";
			return -1;
		}
		netInfo_array = con_manager.getAllNetworkInfo();
		if (netInfo_array == null)
		{
			State_Connection_Message = "no networkinfo availible";
			return -1;
		}
		Integer i =0;
		String net_info_Name ="";
		boolean One_Is_Connected = false;
        for (i = 0; i < netInfo_array.length; i++) {
        	
        	if ( netInfo_array[i].isConnected() )
        	{
        		One_Is_Connected = true;
        		net_info_Name = netInfo_array[i].getTypeName();
        		if ( net_info_Name.equalsIgnoreCase("WIFI"))
        		{
        			State_Connection_Message = "WIFI is Active High Res.";
        			NetworkSpeed_Availible = 1;
        			return 1;
        		}
        		else if  ( net_info_Name.equalsIgnoreCase("MOBILE"))
        		{
        			Integer sub_type = netInfo_array[i].getSubtype();
        			if  (( sub_type == TelephonyManager.NETWORK_TYPE_HSDPA ) || ( sub_type == TelephonyManager.NETWORK_TYPE_UMTS ))
        			{
	        			State_Connection_Message = "UMTS is Active middle Res.";
	        			NetworkSpeed_Availible = 2;
	        			return 2;
        			}
        			else if ( sub_type == TelephonyManager.NETWORK_TYPE_EDGE )
        			{
	        			State_Connection_Message = "EDGE is Active low Res.";
	        			NetworkSpeed_Availible = 3;
	        			return 3;
        			}
        			else
        			{
	        			State_Connection_Message = "no possible connection :-(";
	        			NetworkSpeed_Availible = 4;
	        			return 4;
        			}
        		}
        	}
        }
        if (!One_Is_Connected )
        {
			State_Connection_Message = "no possible connection :-(";
			NetworkSpeed_Availible = 0;
			return 0;
        }
    	
    	return -1;
    }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	  if (resultCode == Activity.RESULT_OK && requestCode == 1) 
	  {
		  Coming_from_Player = true;
	  }
	}
	
    public void AddEntry_recording(String name, String desc) {
        HashMap<String,String> newitem = new HashMap<String,String>();
        newitem.put( "recording_name", name );
        newitem.put( "recording_desc", desc );
        list_recording.add( newitem );
  }

    public void RefreshList_recording() 
    {
      SimpleAdapter adapEntries_recording = new SimpleAdapter(
             this,
             list_recording,
             R.layout.recording_row,
             new String[] { "recording_name", "recording_desc" },
             new int[] { R.id.txtRecordingName, R.id.txtRecordingDesc}
             );
        setListAdapter(adapEntries_recording);
    } 
    
    @Override
    protected void onListItemClick(ListView l,View v,int position,long id) 
    {
    	Selected_Recording_Index = position;
    	
		 AlertDialog.Builder ad = new AlertDialog.Builder( this );
		 ad.setTitle( "Start streaming...?" );
     	if ( !Use_AutoSpeed )
    	{
			Integer Speed = Check_Network();
			Integer Pre_Select = 0;
			if ( Speed == 1)
			{
				Use_High = true;
				Use_Middle = false;
				Use_Low = false;
				Pre_Select = 0;
			}
			else if ( Speed == 2)
			{
				Use_High = false;
				Use_Middle = true;
				Use_Low = false;
				Pre_Select = 1;
			}
			else if ( Speed == 3)
			{
				Use_High = false;
				Use_Middle = false;
				Use_Low = true;
				Pre_Select = 2;
			}
			else
			{
				Use_High = false;
				Use_Middle = false;
				Use_Low = true;
				Pre_Select = 2;
			}
			 final String[] items_question_coonection = {"Fast", "Middle", "Slow"};
			 ad.setSingleChoiceItems(items_question_coonection , Pre_Select, new DialogInterface.OnClickListener() 
			 {
			        public void onClick(DialogInterface dialog, int item)
			        {
				          if ( item == 0)
				          {
								Use_High = true;
								Use_Middle = false;
								Use_Low = false;
				          }
				          else if ( item == 1)
				          {
								Use_High = false;
								Use_Middle = true;
								Use_Low = false;
				          }
				          else if ( item == 2)
				          {
								Use_High = false;
								Use_Middle = false;
								Use_Low = true;
				          }
			        }
		    });
			 ad.setPositiveButton( "Yes", new DialogInterface.OnClickListener() 
			 {
	             public void onClick(DialogInterface dialog, int id) 
	             {
	        	     PlayerProcessing();
	             }
			 });
			 ad.setNegativeButton( "No",  new DialogInterface.OnClickListener() 
			 {
	             public void onClick(DialogInterface dialog, int id) 
	             {
	            	 return;
	             }
			 });
			 ad.show();
    	}
    } 
	
    private void RecordingProcessing() 
    {
    	Error_Description = "";
        Thread thread =  new Thread(null, doBackgroundRecording, "GenerateRecording");
        try
        {
        	File_Handler = new File
  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_recording.htm");
	        if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch ( Exception ex)
        {
        }
        myProgressDialog = ProgressDialog.show(Recordings.this,    
              "Please wait...", "downloading files...", true);
        thread.start();
   }

    private Runnable doBackgroundRecording = new Runnable(){
    	public void run()
    	{
	            try
	            {
	            	downloadFile(4,"");
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 myProgressDialog.setMessage("parsing files...");
	                	 }
	                	 else
	                	 {
		                     myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 return;
	                	 }
	                 }        
	            	});
			if ( Error_Description == "" )
			{
	            try
	            {
	            	read_recordings();
	            } 
	            catch (Exception ex) 
	            {  
	            	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 try
	                		 {
	                			 RefreshList_recording();
	                			 myProgressDialog.dismiss();
	                		 }
	                		 catch ( Exception ex)
	                		 {
	                		 
	                		 }
	                	 }
	                	 else
	                	 {
	                		 myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                	 }
	                 }        
	          });
			}
    	}
  }; 

  	private void read_recordings() throws IOException
  	{
  		File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_recording.htm");
    	if ( Recording_Name == null)
    		Recording_Name = new ArrayList<String>();
    	else
    		Recording_Name.clear();
    	if ( Recording_Url == null)
    		Recording_Url  = new ArrayList<String>();
    	else
    		Recording_Url.clear();
    	if ( Recording_Description == null)
    		Recording_Description  = new ArrayList<String>();
    	else
    		Recording_Description.clear();
        Integer StartPosInLine = 0;
        try {
            if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) {
                BufferedReader r = null;
    			if ( Use_UTF8 )
    				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
    			else
    				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
                while ((myLine =r.readLine()) != null) 
                {
                    StartPosInLine = 0;
                    if (myLine.contains("?REC?") )
                    {
                    	while (StartPosInLine >= 0)
                    	{
	                    	StartPos = myLine.indexOf("?RECTITLE?", StartPosInLine);
	                    	if (StartPos >0 )
	                    	{
		                    	StartPos = StartPos + "?RECTITLE?".toString().length();
		                    	EndPos = myLine.indexOf("?RECSUBTITLE?", StartPos);
		                    	Rec_Name = myLine.substring(StartPos, EndPos);
		                    	StartPos = EndPos;
		                    	Recording_Name.add(Rec_Name);
		                    	StartPos = myLine.indexOf("?RECSUBTITLE?", StartPos);
		                    	StartPos = StartPos + "?RECSUBTITLE?".toString().length();
		                    	EndPos = myLine.indexOf("?PATH?", StartPos);
		                    	Rec_Subtitle = myLine.substring(StartPos, EndPos);
		                    	StartPos = EndPos;
		                    	Recording_Description.add(Rec_Subtitle);
		                    	StartPos = myLine.indexOf("?PATH?", StartPos);
		                    	StartPos = StartPos + "?PATH?".toString().length();
		                    	EndPos = myLine.indexOf("?END?", StartPos);
		                    	Rec_Url = myLine.substring(StartPos, EndPos);
		                    	Recording_Url.add(Rec_Url);
		                    	StartPosInLine = EndPos;
	                    	}
	                    	else
	                    	{
	                    		StartPosInLine = -1;
	                    	}
                    	}
                    }
                }
                
                for (n = 0; n < Recording_Name.size(); n++) {
                	if ( Recording_Description.size() < n )
                		AddEntry_recording(Recording_Name.get(n), "");
                	else
                		AddEntry_recording(Recording_Name.get(n), Recording_Description.get(n));
                }
            }
        }
        catch (Exception ex)
        {
        	Recording_Name.clear();
        	Recording_Description.clear();
        	Recording_Url.clear();
        	Error_Description = ex.toString();
        	System.out.println(ex.toString());
        }
        finally 
        {
        }

  	}
  	
    private void PlayerProcessing() 
    {
        Thread thread =  new Thread(null, doBackgroundPlayer, "GenerateStream");
        try
        {
        	File_Handler = new File
      		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm");
	        if (File_Handler.exists() ) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch (Exception ex)
        {
        	System.out.println(ex.toString());
        	return;
        }
        
        thread.start();
        
        myProgressDialog = ProgressDialog.show(Recordings.this,    
              "Please wait...", "starting stream...", true);
        
   }

    private Runnable doBackgroundPlayer = new Runnable(){
    	public void run()
    	{

            try
            {
            	if ( Use_AutoSpeed )
            	{
        			Integer Speed = Check_Network();
        			switch (Speed)
        			{
        				case 1:
    	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+H";
        					break;
        				case 2:
    	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+M";
        					break;
        				case 3:
    	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+L";
        					break;
    					default:
    						Error_Description = "No network availible!";
    						break;
        			}
            	}
            	else
            	{
            		if ( Use_High )
            		{
	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+H";
            		}
            		else if (Use_Middle)
            		{
	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+M";
            		}
            		else if (Use_Low)
            		{
	    				URL_start_vlc = URL_mvdr + "?vod+" + Recording_Url.get(Selected_Recording_Index)+"+L";
            		}
            	}
            } 
            catch (Exception ex) 
            {  
            	System.out.println(ex.toString());
            }
    		
	            try
	            {
	            	downloadFile(2,URL_start_vlc);
		   	       	if ( Error_Description == "" )
			    	{
		   	       		Thread.sleep(1000);
		   	       		read_play_vlc();
			    	}
		   	       	
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }

	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                	 if ( Error_Description == "" )
	                	 {
	                		 Intent int_setting = new Intent();
	                		 int_setting.putExtra( "STREAM_URL",URL_stream);
	                		 int_setting.putExtra( "URL",URL_mvdr);
	                		 int_setting.setClass(getApplicationContext(),player.class);
	                		 myProgressDialog.dismiss();
	                		 startActivityForResult(int_setting,1);
	                	 }
	                	 else
	                	 {
		                     myProgressDialog.dismiss();
	                		 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                		 messageToast.show();
	                		 return;
	                	 }
	                }        
	            	});

    		
    	}
  }; 
  
  	private void read_play_vlc()
  	{
  		Boolean VLC_is_Streaming = false;
        File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm" );
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                	try
                	{
                        BufferedReader r = null;
            			if ( Use_UTF8 )
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
            			else
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
	                    while ((myLine =r.readLine()) != null)
	                    {
					        if (myLine.contains("done play :-)") )
					        {
					        	VLC_is_Streaming = true;
					        }
						}
                	}
                	catch ( Exception ex )
                	{
                		Error_Description = ex.getMessage().toString();
                		return;
                	}
                }
        }
        finally 
        {
        }
        if ( !VLC_is_Streaming)
        {
        	Error_Description = "Error start streaming";
        }
    	
        if (File_Handler.exists())
        	File_Handler.delete();

  	}
  	
 	private void PlayerStopProcessing() 
    {
        Thread thread =  new Thread(null, doBackgroundPlayer_Stop, "StopStream");
        try
        {
        	File_Handler = new File
      		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm");
	        if (File_Handler.exists() ) 
	        {
	        	File_Handler.delete();
	        }
        }
        catch (Exception ex)
        {
        	System.out.println(ex.toString());
        	return;
        }
        
        
        myProgressDialog = ProgressDialog.show(this,    
              "Please wait...", "stoping stream...", true);
        
        thread.start();
        
   }

    private Runnable doBackgroundPlayer_Stop = new Runnable(){
    	public void run()
    	{
	            try
	            {
	            	 downloadFile(3,"");
	               	 if ( Error_Description == "" )
	            	 {
	            		myProgressDialog.setMessage("parsing files...");
	 	            	read_stop_vlc();
	            	 }
	            } 
	            catch (Exception ex) 
	            {  
                	System.out.println(ex.toString());
	            }
	          
	            runOnUiThread(new Runnable() {
	                 @Override
	                 public void run() {
	                     myProgressDialog.dismiss();
	                     if ( Error_Description != "" )
	                     {
	                    	 Toast messageToast = Toast.makeText(getApplicationContext(), Error_Description, Toast.LENGTH_LONG);
	                    	 messageToast.show();
	                     }
	                 }        
	            	});

    		
    	}
  }; 
  	
	private void read_stop_vlc()
  	{
  		Boolean VLC_is_Stoped = false;
        File_Handler = new File
  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm" );
        try 
        {
                if (File_Handler.exists() && File_Handler.canRead() && File_Handler.length() > 0) 
                {
                    try 
                    {
                        BufferedReader r = null;
            			if ( Use_UTF8 )
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "UTF8" ) );
            			else
            				r = new BufferedReader( new InputStreamReader( new FileInputStream(File_Handler), "iso-8859-1") );
	                    while ((myLine =r.readLine()) != null)
						{
					        if (myLine.contains("done stop :-)") )
					        {
					        	VLC_is_Stoped = true;
					        }
						}
					} 
                    catch (Exception ex) 
					{
                    	Error_Description = ex.getMessage().toString();
					}
                }
        }
        finally 
        {
        }
        if ( VLC_is_Stoped )
        {
	    	Toast toast = Toast.makeText(getApplicationContext(), "VLC is streaming stoped", Toast.LENGTH_LONG);
	    	toast.show();
        }
  	}

  	private Boolean downloadFile(Integer download_mode, String URL_for_VDR)
  	{
  		if ( Check_Passwd )
  		{
  			login = HTML_User;
  			password = HTML_Passwd;
  		}
  		else
  		{
  			login = "";
  			password = "";
  		}
		Authenticator.setDefault(new Authenticator() 
		{
		    protected PasswordAuthentication getPasswordAuthentication() 
		    {
		    	PasswordAuthentication mypas = null;
		    	try
		    	{
		    		mypas = new PasswordAuthentication (login, password.toCharArray());
		    	}
		    	catch (Exception ex )
		    	{
		    		Log.e("mypas", ex.toString());
		    	}
		        return mypas;
		    }
		});
  		Error_Description = "";
    	switch (download_mode)
    	{
    		// Bouquet-�bersicht
    		case 0:
    			break;
    			
    	   		// VLC play
    		case 2:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_for_VDR);
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	        File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/play.htm" );

    	  	  		if (!File_Bouquet.exists())
    	  	  			File_Bouquet.createNewFile();
    	  	  		
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
	    	  	        
    	  	        byte[] buffer = new byte[1024];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) != -1 ) {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  		}
    	  		catch (IOException ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;

        		// VLC is Stoping
    		case 3:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?stop");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	        File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/stop.htm" );

    	  	  		if (!File_Bouquet.exists())
    	  	  			File_Bouquet.createNewFile();
    	  	  		
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
	    	  	        
    	  	        byte[] buffer = new byte[1024];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) != -1 ) {
    	  	        	fileOutput.write(buffer,0, len1);
    	  	        }
    	  	        
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();

    	  	        
    	  		}
    	  		catch (IOException ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;

    		case 4:
    	  		try
    	  		{
    	  			URL url_mvdr = new URL(URL_mvdr + "?rec");
    	  	        HttpURLConnection connection_mvdr = (HttpURLConnection) url_mvdr.openConnection();
    	  	        connection_mvdr.setConnectTimeout(10000);
    	  	        connection_mvdr.setRequestMethod("GET");
    	  	        connection_mvdr.setDoOutput(true);
    	  	        connection_mvdr.connect();

    	  	  		File File_Bouquet = new File
    	  	  		(Environment.getExternalStorageDirectory().getPath()+"/mvdr/mvdr_recording.htm");
    	  	        FileOutputStream fileOutput = new FileOutputStream(File_Bouquet);
    	  	        
    	  	        InputStream input_mvdr = connection_mvdr.getInputStream();
    	  	      
    	  	        byte[] buffer = new byte[8192];
    	  	        int len1 = 0;
    	  	        while ( (len1 = input_mvdr.read(buffer)) > 0 ) 
    	  	        {
    	  	        	fileOutput.write(buffer,0, len1);
        	  	        fileOutput.flush();
    	  	        }
    	  	        fileOutput.close();
    	  	        input_mvdr.close();
    	  	        connection_mvdr.disconnect();
    	  	        
    	  		}
    	  		catch (Exception ex) 
    	  		{
                	System.out.println(ex.toString());
                	Error_Description = ex.getMessage().toString();
    	            return false;
    	  		}
    			return true;
    			
    	}
		return true;
  	}


}
